<template>
  <div :style="{ padding: '0 0 32px 32px' }">
    <h4 :style="{ marginBottom: '20px' }">{{ title }}</h4>
    <v-chart :forceFit="true" :height="height" :data="data" :onClick="handleClick">
      <v-coord type="rect" direction="LT" />
      <v-tooltip />
      <v-legend />
      <v-axis dataKey="y" position="right" />
      <v-axis :dataKey="xField" :label="label" />
      <v-bar :position="position" :color="this.yField?fields[0]:'x'" :adjust="adjust" />
    </v-chart>
  </div>
</template>

<script>
import { DataSet } from '@antv/data-set'
import { ChartEventMixins } from './mixins/ChartMixins'

export default {
  name: 'TransverseBarMuiltid',
  mixins: [ChartEventMixins],
  props: {
    title: {
      type: String,
      default: ''
    },
    dataSource: {
      type: Array,
      default: () => [
        { label: 'Mon.', series1: 2800, series2: 2260 },
        { label: 'Tues.', series1: 1800, series2: 1300 },
        { label: 'Wed.', series1: 950, series2: 900 },
        { label: 'Thur.', series1: 500, series2: 390 },
        { label: 'Fri.', series1: 170, series2: 100 }
      ]
    },
    fields: {
      type: Array,
      default: () => ['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.']
    },
    // 别名，需要的格式：[{field:'name',alias:'姓名'}, {field:'sex',alias:'性别'}]
    aliases: {
      type: Array,
      default: () => []
    },
    height: {
      type: Number,
      default: 254
    },
    xField: {
      type: String,
      default: 'type'
    },
    yField: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      label: { offset: 12 },
      adjust: [{ type: 'dodge', marginRatio: 1 / 32 }],
      position: this.xField + '*' + (this.yField ? this.yField : 'y')
    }
  },
  computed: {
    data() {
      if (this.yField) {
        return this.dataSource
      }
      const dv = new DataSet.View().source(this.dataSource)
      console.log('dataSource', this.dataSource)
      dv.transform({
        type: 'fold',
        fields: this.fields,
        key: 'x',
        value: 'y'
      })
      // bar 使用不了 - 和 / 所以替换下
      const rows = dv.rows.map(row => {
        if (typeof row.x === 'string') {
          row.x = row.x.replace(/[-/]/g, '_')
        }
        return row
      })
      // 替换别名
      rows.forEach(row => {
        for (const item of this.aliases) {
          if (item.field === row.x) {
            row.x = item.alias
            break
          }
        }
      })
      return rows
    }
  }
}
</script>
